<!--
value           =====>   双向数据绑定，v-model
multiple        =====>   是否多选
params          =====>   远程数据默认请求参数，object，如：
                         type：department只查询部门，department_personnel查询部门和部门下人员
                         status：1 在职 的，2离职的
                         selected：已经选择的逗号隔开
placeholder     =====>   单选，input的placeholder
title           =====>   多选，modal的标题
buttonTitle     =====>   多选，按钮的标题

Method
change          =====>   单选，确认选择时
ok              =====>   多选，点击确认时
cancel          =====>   多选，点击取消时

slot（仅多选时支持）
-->
<template>
  <div class="choose-department-or-person-modal">
    <template v-if="multiple">
      <slot v-if="$slots.default"></slot>
      <template v-else>
        <a-button @click="open">{{ buttonTitle }}</a-button>
      </template>
      <div class="base-flex base-rows base-wrap base-align-items-center">
        <!--      <span>已选择{{ checkedKeys.length }}项</span>-->
        <a-tag closable @close="onCloseChecked(item)" v-for="(item, index) in checkedRows" :key="index" class="base-mt5 base-mr3">{{ item.title }}</a-tag>
      </div>
      <a-modal v-model:open="visible" :title="title" width="680px">
        <a-row :gutter="[16]">
          <a-col span="12">
            <a-input-search v-model:value="searchValue" placeholder="请输入关键字" class="base-mb15" />
            <div class="base-text-right">
              <a-button type="link" @click="expandAll">
                <ExpandAltOutlined /> 展开
              </a-button>
              <a-button type="link" @click="expandNone"><ExpandOutlined /> 收起</a-button>
            </div>
            <a-tree
                :auto-expand-parent="autoExpandParent"
                :expanded-keys="expandedKeys"
                v-model:checkedKeys="checkedKeys"
                checkable
                :tree-data="treeData"
                :fieldNames="{ key:'id', title:'title', children:'children' }"
                @expand="onExpand"
            >
              <template #title="{ title }">
            <span v-if="title.indexOf(searchValue) > -1">
              {{ title.substr(0, title.indexOf(searchValue)) }}
              <span class="base-text orange">{{ searchValue }}</span>
              {{ title.substr(title.indexOf(searchValue) + searchValue.length) }}
            </span>
                <span v-else>{{ title }}</span>
              </template>
            </a-tree>
          </a-col>
          <a-col span="12">
            <div class="choose-wrapper">
              <div class="title base-mb10"> 已选择 <span class="base-text primary">{{ checkedKeys.length }}</span> 项 </div>
              <a-tag color="blue" closable @close="onCloseChecked(item)" v-for="(item, index) in checkedRows" :key="index">{{ item.title }}</a-tag>
            </div>
          </a-col>
        </a-row>

        <template #footer>
          <div class="base-flex base-rows base-align-items-center base-justify-content-center">
            <a-button key="back" @click="handleCancel">取消</a-button>
            <a-button key="submit" type="primary" :loading="loading" @click="handleOk">确定</a-button>
          </div>
        </template>

      </a-modal>
    </template>

    <template v-else>
      <a-cascader
          :field-names="{ label:'title', value:'id', children:'children' }"
          :placeholder="placeholder"
          :options="treeData"
          v-model:value="defaultValue"
          @change="onChange"
          allow-clear
          show-search
      />
    </template>
  </div>
</template>

<script setup>
import { getCurrentInstance, onMounted, ref, watch } from 'vue'
import { ExpandAltOutlined } from '@ant-design/icons-vue'
const { proxy } = getCurrentInstance()
const $TOOL = proxy.$TOOL

const emit = defineEmits(['ok', 'cancel', 'update:value', 'change'])
const props = defineProps({
  value: {
    type: Array,
    default: []
  },
  multiple: {
    type: Boolean,
    default: false
  },
  params: {
    type: Object,
    default: () => {}
  },
  title: {
    type: String,
    default: '选择部门'
  },
  buttonTitle: {
    type: String,
    default: '选择部门'
  },
  placeholder: {
    type: String,
    default: '选择部门'
  }
})
const visible = ref(false)
const loading = ref(false)
// 单选
const defaultValue = ref([])
// 多选
const searchValue = ref('')
const expandedKeys = ref([]) // 受控）展开指定的树节点
const autoExpandParent = ref(false) // 是否自动展开父节点
const checkedKeys = ref([])
const checkedRows = ref([])
const treeData = ref([
  {
    "id": 1,
    "merchant_code": "2T67P95ARC",
    "title": "百度",
    "pid": 0,
    "leader_id": 2,
    "phone": "13337803337",
    "remark": "",
    "status": 1,
    "create_time": 0,
    "update_time": 1657883570,
    "leader": "刘强强",
    "children": [
      {
        "id": 5,
        "merchant_code": "2T67P95ARC",
        "title": "销售部",
        "pid": 1,
        "leader_id": 3,
        "phone": "13655198393",
        "remark": "",
        "status": 1,
        "create_time": 0,
        "update_time": 1657690643,
        "leader": "吕珊珊",
        "children": [
          {
            "id": 8,
            "merchant_code": "2T67P95ARC",
            "title": "销售",
            "pid": 5,
            "leader_id": 114,
            "phone": "",
            "remark": "",
            "status": 1,
            "create_time": 0,
            "update_time": 1679297663,
            "leader": "何京楠"
          },
          {
            "id": 9,
            "merchant_code": "2T67P95ARC",
            "title": "大客销售部",
            "pid": 8,
            "leader_id": 0,
            "phone": "",
            "remark": "",
            "status": 1,
            "create_time": 0,
            "update_time": 1663750767,
            "leader": null
          },
        ]
      },
      {
        "id": 7,
        "merchant_code": "2T67P95ARC",
        "title": "运营部",
        "pid": 1,
        "leader_id": 0,
        "phone": "",
        "remark": "",
        "status": 1,
        "create_time": 0,
        "update_time": 1657696804,
        "leader": null,
        "children": [
          {
            "id": 14,
            "merchant_code": "2T67P95ARC",
            "title": "标准代运营",
            "pid": 7,
            "leader_id": 0,
            "phone": "",
            "remark": "",
            "status": 1,
            "create_time": 0,
            "update_time": 1657696808,
            "leader": null
          },
          {
            "id": 15,
            "merchant_code": "2T67P95ARC",
            "title": "深度代运营",
            "pid": 7,
            "leader_id": 0,
            "phone": "",
            "remark": "",
            "status": 1,
            "create_time": 0,
            "update_time": 1683254191,
            "leader": null
          },
          {
            "id": 17,
            "merchant_code": "2T67P95ARC",
            "title": "设计部",
            "pid": 7,
            "leader_id": 0,
            "phone": "",
            "remark": "",
            "status": 1,
            "create_time": 0,
            "update_time": 0,
            "leader": null
          },
          {
            "id": 18,
            "merchant_code": "2T67P95ARC",
            "title": "文案部",
            "pid": 7,
            "leader_id": 0,
            "phone": "",
            "remark": "",
            "status": 1,
            "create_time": 0,
            "update_time": 1684748944,
            "leader": null
          },
        ]
      },
      {
        "id": 16,
        "merchant_code": "2T67P95ARC",
        "title": "行政部",
        "pid": 1,
        "leader_id": 0,
        "phone": "",
        "remark": "",
        "status": 1,
        "create_time": 0,
        "update_time": 0,
        "leader": null,
        "children": [
          {
            "id": 2,
            "merchant_code": "2T67P95ARC",
            "title": "人事部",
            "pid": 16,
            "leader_id": 5,
            "phone": "17366238505",
            "remark": "",
            "status": 1,
            "create_time": 0,
            "update_time": 1657696482,
            "leader": "李玉玲"
          },
          {
            "id": 3,
            "merchant_code": "2T67P95ARC",
            "title": "财务部",
            "pid": 16,
            "leader_id": 14,
            "phone": "17366090904",
            "remark": "",
            "status": 1,
            "create_time": 0,
            "update_time": 1657696491,
            "leader": "王习"
          },
        ]
      },
    ]
  },
  {
    "id": 69,
    "merchant_code": "2T67P95ARC",
    "title": "网易",
    "pid": 0,
    "leader_id": 0,
    "phone": "",
    "remark": null,
    "status": 1,
    "create_time": 1697784937,
    "update_time": 0,
    "leader": null,
    "children": [
      {
        "id": 65,
        "merchant_code": "2T67P95ARC",
        "title": "商务部",
        "pid": 69,
        "leader_id": 0,
        "phone": "",
        "remark": null,
        "status": 1,
        "create_time": 1677750122,
        "update_time": 1697784978,
        "leader": null
      },
    ]
  }
])
const dataList = []

// 单选
// watch(() => props.value, (curr, old) => {
//   console.log('值有变化', props.value)
//   // defaultValue.value = curr
// })

// 多选
watch(searchValue, curr => {
  const expanded = dataList.map(item => {
    if (item.title.indexOf(curr) > -1) {
      return getParentId(item.id, treeData.value);
    }
    return null;
  })
      .filter((item, i, self) => item && self.indexOf(item) === i);

  expandedKeys.value = expanded;
  autoExpandParent.value = true
});
watch(checkedKeys, curr => {
  const rows = dataList.map(item => {
    if ($TOOL.array.arrayIndexOf(curr, item.id) > -1) {
      return item;
    }
    return null;
  }).filter((item) => item && item.id)
  checkedRows.value = rows
});

onMounted(() => {
  if(props.multiple) {
    generateList(treeData.value)
  }else{
    // console.log(treeData.value)
    // defaultValue.value = props.value
  }
})

// 单选
const onChange = (value,selectedOptions) => {
  console.log(value)
  emit('change', value, selectedOptions)
  emit('update:value', value)
}

// 多选
const expandAll = () => {
  // 展开全部
  expandedKeys.value = dataList.map(ele => {
    return ele.id
  })
  autoExpandParent.value = true
}
const expandNone = () => {
  expandedKeys.value = []
  autoExpandParent.value = false
}

const generateList = (tree) => {
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i]
    dataList.push({
      id: node.id,
      title: node.title
    })
    if (node.children) {
      generateList(node.children)
    }
  }
}
const getParentId = (id, tree) => {
  let parentId
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i]
    if (node.children) {
      if (node.children.some(item => item.id === id)) {
        parentId = node.id
      } else if (getParentId(id, node.children)) {
        parentId = getParentId(id, node.children)
      }
    }
  }
  return parentId
}
const onExpand = (ids) => {
  expandedKeys.value = ids;
  autoExpandParent.value = false;
}
const onCloseChecked = (item) => {
  const id = item.id
  const checked = checkedKeys.value
  checked.splice(checked.indexOf(id), 1)
}

const handleOk = () => {
  emit('update:value', checkedKeys.value)
  emit('ok', checkedKeys.value, checkedRows.value)
  loading.value = true
  setTimeout(() => {
    loading.value = false
    close()
  }, 200)
}
const handleCancel = () => {
  emit('cancel')
  close()
}
const open = () => {
  visible.value = true
}
const close = () => {
  visible.value = false
  searchValue.value = ''
  // checkedKeys.value = []
  setTimeout(() => {
    expandNone()
  },100)
}
defineExpose({ open, close })
</script>

<style lang="scss" scoped>
.choose-wrapper {
  border-left: 1px solid #f0f0f0;
  border-radius: 2px;
  padding: 5px 20px;
  height: 100%;
  .ant-tag {
    margin: 5px 5px 5px 0;
  }
}
</style>
